﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using PocketPond.PondConsumer;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace PondConsumer
{
    public class Avatar
    {
        public static Boolean downloadAvatar(String url, String filename)
        {
            MemoryStream ArtWriter = new MemoryStream();
            try
            {
                HttpWebRequest GetArt = WebRequestFactory.CreateHttpRequest(url);
                GetArt.Timeout = 20000;
                HttpWebResponse ArtResponse = (HttpWebResponse)GetArt.GetResponse();

                Stream responseStream = null;

                responseStream = ArtResponse.GetResponseStream();

                int count = 0;
                var buffer = new byte[8192];
                do
                {
                    count = responseStream.Read(buffer, 0, buffer.Length);
                    if (count != 0)
                    {
                        ArtWriter.Write(buffer, 0, count);
                    }
                } while (count != 0);
                responseStream.Close();

                ArtWriter.Seek(0, SeekOrigin.Begin);
                Bitmap bmp = new Bitmap(ArtWriter);

                String strDir = PocketPond.Core.Utils.getPocketPondDir() + "\\avatars";
                if (!Directory.Exists( strDir ))
                {
                    Directory.CreateDirectory(strDir);
                }
                
                FileStream fStream = File.Create(filename);

                bmp.Save(fStream, ImageFormat.Png);
                fStream.Close();
                ArtWriter.Close();
                return true;
            }
            catch (Exception ex)
            {
                // TODO something?
                ArtWriter.Close();
                return false;
            }
        }
    }
}
